package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.model.db.User;
import com.tanhua.model.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 统一token处理类
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 前置处理（controller之前）
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //主要就是方便调试看打印信息
        //记录请求的路径
        String requestMethod = request.getMethod();
        log.info("请求了路径: {}:{}",requestMethod, request.getRequestURI());
        if(handler instanceof HandlerMethod) {
            // 找出调用的哪个controller中的方法
            HandlerMethod method = (HandlerMethod) handler;
            if(null != method) {
                log.info("执行了: " + method.getShortLogMessage());
            }
        }

        //1根据key查询redis看用户是否登录
        String token = request.getHeader("Authorization");
        String tokenKey = "TOKEN_"+token;
        String userStr = stringRedisTemplate.opsForValue().get(tokenKey);
        if(!StringUtils.isEmpty(userStr)){
            //2如果用户已经登录，获取用户信息存入ThreadLocal对象中（UserHolder）
            User user = JSON.parseObject(userStr, User.class);
            if(user != null){
                //为了提升用户体验 给用户续期
                stringRedisTemplate.expire(tokenKey,1, TimeUnit.DAYS);
                UserHolder.setUser(user);//使用UserHolder.getUser();
                log.debug("****************token统一处理成功了{}**********************",user.toString());
                return true;
            }
        }
        //3如果用户未登录，直接返回false 设置权限不足状态码401
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        log.debug("**************用户未登录************"+tokenKey);
        return false;
    }

    /**
     * controller发生异常，照样执行
     * 移除线程中的对象
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
